package com.aat.dxfy.jiajiemi;

import java.io.ByteArrayOutputStream;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class SafeTools {

	public static byte[] aesEncryptToByte(String content, String password) {
		try {
			Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] aesDecryptToByte(byte[] content, String password) {
		try {
			Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(content);
			return result; // 加密
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String aesJiami(String content, String pwd) {
		byte[] encryptResult = aesEncryptToByte(content, pwd);
		return parseByte2HexStr(encryptResult);
	}

	public static String aesJiemi(String content, String pwd) {
		byte[] decryptFrom = parseHexStr2Byte(content);
		byte[] decryptResult = aesDecryptToByte(decryptFrom, pwd);
		return new String(decryptResult);
	}

	private static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	private static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

	private static char[] daoxu(char[] cs) {
		int length = cs.length;
		char[] csp = new char[length];
		for (int i = 0; i < length; i++) {
			csp[i] = cs[length - 1 - i];
		}
		return csp;
	}

	private static char[] dschg(char[] cs) {
		int length = cs.length;
		char[] csp = new char[length];
		for (int i = 0; i < length / 2; i++) {
			csp[2 * i] = cs[2 * i + 1];
			csp[2 * i + 1] = cs[2 * i];
		}
		if (length % 2 != 0) {
			csp[length - 1] = cs[length - 1];
		}
		return csp;
	}

	private static String birthWebCode(int n) {
		String s = "";
		String st = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		char[] str = st.toCharArray();
		for (int i = str.length - 1; i >= str.length - n; i--) {
			int k = (int) (Math.random() * i);
			char t = str[k];
			str[k] = str[i];
			str[i] = t;
			s += t;
		}
		return s;
	}

	private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
			5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26,
			27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
			-1, -1, -1 };

	private static byte[] decode(String str) {
		byte[] data = str.getBytes();
		int len = data.length;
		ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
		int i = 0;
		int b1, b2, b3, b4;

		while (i < len) {
			do {
				b1 = base64DecodeChars[data[i++]];
			} while (i < len && b1 == -1);
			if (b1 == -1) {
				break;
			}

			do {
				b2 = base64DecodeChars[data[i++]];
			} while (i < len && b2 == -1);
			if (b2 == -1) {
				break;
			}
			buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4)));

			do {
				b3 = data[i++];
				if (b3 == 61) {
					return buf.toByteArray();
				}
				b3 = base64DecodeChars[b3];
			} while (i < len && b3 == -1);
			if (b3 == -1) {
				break;
			}
			buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));

			do {
				b4 = data[i++];
				if (b4 == 61) {
					return buf.toByteArray();
				}
				b4 = base64DecodeChars[b4];
			} while (i < len && b4 == -1);
			if (b4 == -1) {
				break;
			}
			buf.write((int) (((b3 & 0x03) << 6) | b4));
		}
		return buf.toByteArray();
	}

	private static String encode64(String input) {
		String keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		String output = "";
		int chr1 = 0, chr2 = 0, chr3 = 0;
		int enc1, enc2, enc3, enc4;
		int i = 0;
		while (i < input.length()) {
			chr1 = (int) input.toCharArray()[i++];
			enc1 = chr1 >> 2;
			if (i >= input.length()) {
				enc2 = ((chr1 & 3) << 4);
				enc3 = enc4 = 64;
			} else {
				chr2 = (int) input.toCharArray()[i++];
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				if (i >= input.length()) {
					enc3 = ((chr2 & 15) << 2);
					enc4 = 64;
				} else {
					chr3 = (int) input.toCharArray()[i++];
					enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
					enc4 = chr3 & 63;
				}
			}
			output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
			chr1 = chr2 = chr3 = 0;
			enc1 = enc2 = enc3 = enc4 = 0;
		}
		return output;
	}

	public static String aatJiami(String pwd) {
		String str = birthWebCode(6) + pwd + birthWebCode(6);
		char[] cs = str.toCharArray();
		cs = daoxu(cs);
		cs = dschg(cs);
		String sha = birthWebCode(3) + encode64(new String(cs)) + birthWebCode(3);
		return sha;
	}

	public static String aatJiemi(String sha) {
		sha = sha.substring(3, sha.length() - 3);
		String str = new String(decode(sha));
		char[] cs = str.toCharArray();
		cs = dschg(cs);
		cs = daoxu(cs);
		String pwd = new String(cs);
		pwd = pwd.substring(6, pwd.length() - 6);
		return pwd;
	}
	
	

	public static void main(String[] args) {
		System.out.println(aesJiami("中国", "1"));
		System.out.println(aesJiemi("6FB3CF4CAB2A4027D98DD04A63341359", "1"));
		System.out.println(aatJiami("123456"));
		System.out.println(aatJiami("123456"));
		System.out.println(aatJiami("123456"));
		System.out.println(aatJiemi("1mTNzQyODM5NTYzNDEyNjA4NTMxRHf"));
		System.out.println(new String(decode("NTYzNDEy")));
	}

}
